import React, { Component } from 'react';
import { Transfer, Card, message } from 'antd';
import services from '../../../services/api';

class RoleAssign extends Component {
  constructor(props) {
    super(props);
    this.api = 'role';
    this.state = {
      dataSource: [],
      targetKeys: []
    };
  }
  componentDidMount() {
    services[this.api].queryOne({ id: this.props.match.params.id }).then(data => {
      if (data.code === 0) {
        const dataSource = [];
        const targetKeys = [];
        for (let i = 0; i < data.data.selected_permissions.length; i++) {
          dataSource.push({
            key: data.data.selected_permissions[i].id,
            title: data.data.selected_permissions[i].name
          });
          targetKeys.push(data.data.selected_permissions[i].id);
        }
        for (let i = 0; i < data.data.unselected_permissions.length; i++) {
          dataSource.push({
            key: data.data.unselected_permissions[i].id,
            title: data.data.unselected_permissions[i].name
          });
        }
        this.setState({
          dataSource: dataSource,
          targetKeys: targetKeys
        });
      } else {
        message.error(data.msg);
      }
    });
  }
  render() {
    return (
      <div>
        <Card title='权限分配' bordered={false}>
          <Transfer
            dataSource={this.state.dataSource}
            targetKeys={this.state.targetKeys}
            showSearch={true}
            titles={['未分配权限', '已分配权限']}
            locale={{ itemUnit: '项', itemsUnit: '项', searchPlaceholder: '请输入搜索内容' }}
            onChange={this.handleChange}
            render={item => item.title}
            style={{ width: '100%' }}
            listStyle={{
              width: '45%',
              height: 300
            }}
          />
        </Card>
      </div>
    );
  }

  handleChange = (nextTargetKeys, direction, moveKeys) => {
    if (direction === 'right') {
      services[this.api].assign({ id: this.props.match.params.id, item_ids: moveKeys }).then(data => {
        if (data.code === 0) {
          message.success('分配成功');
          this.setState({ targetKeys: nextTargetKeys });
        } else {
          message.error(data.msg);
        }
      });
    } else {
      services[this.api].revoke({ id: this.props.match.params.id, item_ids: moveKeys }).then(data => {
        if (data.code === 0) {
          message.success('分配成功');
          this.setState({ targetKeys: nextTargetKeys });
        } else {
          message.error(data.msg);
        }
      });
    }
  };
}

export default RoleAssign;
